#!/bin/sh
#
# find metrics in the QA archives
#
# command line args are alternate patterns matched in the output
# from pminfo -d ... so metric names and metric descriptors
#

tmp=/var/tmp/$$
sts=0
trap "rm -f $tmp.*; exit \$sts" 0 1 2 3 15

export PCP_DERIVED_CONFIG=

_usage()
{
    echo >&2 "Usage: `basename $0` [options] pat ..."
    echo >&2 "   -a         search archives [default]"
    echo >&2 "   -h         search localhost live metrics"
    echo >&2 "pat ...       are treated as conjuncted, so pat && ..."
}

arch=true
while getopts "ah?" c
do
    case $c
    in
	a)
	    arch=true
	    ;;
	h)
	    arch=false
	    ;;
	?)
	    _usage
	    sts=1
	    exit
	    ;;
    esac
done
shift `expr $OPTIND - 1`

if [ $# -eq 0 ]
then
    _usage
    sts=1
    exit
fi

pat=""
for arg
do
    if [ -z "$pat" ]
    then
	pat="($arg)"
    else
	pat="$pat|($arg)"
    fi
done

if $arch
then
    srclist="`find archives tmparch -name '*.meta*' | sed -e 's/\.meta//'`"
else
    srclist='ignoreme'
fi

_do_info()
{
    pminfo "$@" 2>&1 \
    | sed \
	-e '/^[ 	]*$/d' \
	-e '/^[a-z]/{
s/$/|/
N
s/$/|/
N
s/|./|/g
s/  */ /g
s/| Data Type: /|/
s/ InDom: /|/
s/ Semantics: /|/
s/ Units: /|/
}'
}

for src in $srclist
do
    src_esc=`echo "$src" | sed -e 's;/;\\\\/;g'`
    if $arch
    then
	cached=false
	[ -f ".findmetric/$src" ] && cached=true
	if [ "$cached" = false ]
	then
	    echo >&2 "build cache for $src ..."
	    dir=".findmetric/`dirname "$src"`"
	    [ -d "$dir" ] || mkdir -p "$dir"
	    _do_info -d -a $src >".findmetric/$src"
	fi
	cat ".findmetric/$src"
    else
	_do_info -d
    fi \
    | grep -E "$pat" >$tmp.out

    # so we have matched at least one pat from the command line ...
    # now see if app pat's are matched
    #
    match=true
    for arg
    do
	if grep -q "$arg" $tmp.out
	then
	    :
	else
	    match=false
	    break
	fi
    done

    if $match
    then
	if $arch
	then
	    pmdumplog -l $src >$tmp.info
	    vers=`sed -n <$tmp.info -e '/Log Format Version/{
s/.*Version //
s/)//
p
}'`
	    host=`sed -n <$tmp.info -e '/ from host /{
s/.* from host //
p
}'`
	    echo "=== `echo "$src" | sed -e 's/\.meta$//' -e 's/\.meta\.[^.]*$//'` (V.$vers) host: $host ==="
	    grep commencing $tmp.info
	    grep ending $tmp.info
	    sed <$tmp.out -e "s/^/    /"
	else
	    echo "=== `hostname` ==="
	    sed <$tmp.out -e "s/^/    /"
	fi
    fi
done
